(function($) {
	var defaults = {
		init: false,
		maxHeight: 100,
		maxWidth: 100,
		identify: new Date().getTime(),
		canvascomplete: function(event, image, canvas) {
			var imageType = image.getAttribute('imageType');
			var base64 = canvas.toDataURL(imageType);
			var identify = $(image).data('identify');
			$('#img' + identify).get(0).src = base64;
			$('#hide' + identify).val(base64);
		},
		initopt: function(image) {
			var identify = image.data('identify');
			var div = document.createElement('div');
			div.className = 'testdiv';
			div.innerHTML = ['<div>',
			    '<a href="javascript:void(0)" style="margin-right:10px;" id="rotate', identify , '">旋转图片</a>',      
			    '<a href="javascript:void(0)" id="remove', identify , '">删除图片</a>', ,
				'</div>',
			    '<div style="width:200px;height:200px;">',
			    '<img id="img', identify, '" width="100%" height="100%" src="', '', '"/>',
                '<input id="hide', identify, '" type="hidden" name="images" value="', '', '"/>',
                '</div>'].join('');
			image.parent().append(div);
			image.hide();
			$('#rotate' + identify).bind('click', function(e) {
				e.preventDefault();
				image.trigger('imagerotate');
				return false;
			});
			$('#remove' + identify).bind('click', function(e) {
				e.preventDefault();
				//$('#localmsg > div').remove();
				$(e.target).blur();
			});
		}
	};
	$.fn.imageRotater = function(options) {
		var opts = $.extend({}, defaults, options);
		return this.each(function() {
			var tagName = this.tagName.toLowerCase();//检测需要处理的元素是不是img类型的
			if ('img' != tagName) {
				return;
			}
			var $this = $(this);
			$.loadImage(this,  function() {
				if (!$this.data('initcompleted')) {
					if ($.isFunction(opts.canvascomplete)) {
						$this.bind('canvascomplete', function(event, image, canvas) {
							console.log('receive canvascomplete event.');
							opts.canvascomplete(event, image, canvas);
						});
					}
					$this.bind('imagerotate', function(event) {
						console.log('receive imagerote event.');
						doRotate($this.get(0));
					});
					init(this, opts);
					opts.initopt($this);
					$this.data('initcompleted', true);
					if (opts.init) {
						$this.trigger('imagerotate');
					}
				}
			});
		});
	};
	function init(image, opts) {
		var $this = $(image);
		$this.attr('width', $this.width());
		$this.attr('height', $this.height());
		$this.data('width', $this.width());
		$this.data('height', $this.height());
		$this.data('maxWidth', opts.maxWidth);
		$this.data('maxHeight', opts.maxHeight);
		$this.data('identify', opts.identify);
		$this.data('imageid', 'image_' + opts.identify);
		$this.data('canvasid', 'canvas_' + opts.identify);
		$this.data('image', $.createImage($this.data('imageid')));
		$this.data('canvas', $.createCanvas($this.data('canvasid')));
	}
	function getParamByAngle(angle) {
		var param = {
				x: 0,
				y: 0
			};
		if (0 == angle) {
			param = {
				x: 0,
				y: 0
			};
		} else if (90 == angle) {
			param = {
				x: 0,
				y: -1
			};
		} 
		else if (180 == angle) {
			param = {
				x: -1,
				y: -1
			};
		} else if (270 == angle) {
			param = {
				x: -1,
				y: 0
			};
		}
		return param;
	}
	function rotateImage(image, angle) {
		var param = getParamByAngle(angle);
		var $image = $(image);
		var maxWidth = $image.data('maxWidth');
		var maxHeight = $image.data('maxHeight');
		var width = image.width;
		var height = image.height;
		var scaleX = 1;
		if (width > maxWidth)  {
			scaleX = (maxWidth / width);
			width = maxWidth;
		} 
		var scaleY = 1;
		if (height > maxHeight) { 
			scaleY = (maxHeight / height);
			height = maxHeight;
		}
		var n = image.getAttribute('step');
		if (null == n) {
			n = 0;
		}
		var canvas = $image.data('canvas');
		var context = canvas.getContext('2d');
		if (n % 2 == 0) {
			canvas.setAttribute('width', width); 
			canvas.setAttribute('height', height); 
			context.scale(scaleX, scaleY);
		} else {
			canvas.setAttribute('width', height); 
			canvas.setAttribute('height', width); 
			context.scale(scaleY, scaleX);
		}
		context.rotate(angle * Math.PI / 180); 
		context.drawImage(image, image.width * param.x, image.height * param.y);
		context.save();
		$image.trigger('canvascomplete', [image, canvas]);
	}
	function doRotate(image) {
		var n = image.getAttribute('step');
		if (null == n || n > 3) {
			n = 0;
		}
		rotateImage(image, n * 90);
		n++;
		image.setAttribute('step', n);
	}
	$.extend({
		imageType: function(img) {//取出html img类型图片的类型
			var src = img.src;
			if (/^data:image\/(\w*);base64,.*/.test(src)) {
				src = src.substring(0, 40);
				var m = src.match(/^data:image\/(\w*);base64,.*/);
				return 'image/' + m[1].toLowerCase();
			}
			if (/.*\.(\w*)$/.test(src)) {
				var m = src.match(/.*\.(\w*)$/);
				return 'image/' + m[1].toLowerCase();
			}
			return 'image/png';
		},
		createCanvas: function(id) {
			var canvas = document.getElementById(id);
			if (canvas == null) {
				canvas = document.createElement('canvas'); 
				canvas.setAttribute("id", id);
			}
			return canvas;
		},
		loadImage: function(image, callback) {
			image.src = image.src;
			if (image.complete) {//如果图片已经存在于浏览器缓存，直接调用回调函数
				image.setAttribute('imageType', $.imageType(image));
				callback.call(image);
				return;//直接返回，不用再处理onload事件
			}
			image.onload = function() {//图片下载完毕时异步调用callback函数。
				image.setAttribute('imageType', $.imageType(image));
				callback.call(image);//将回调函数的this替换为Image对象  
			};
		},
		createImage: function(id) {
			var img = document.getElementById(id);
			if (null == img) {
				img = document.createElement('img');
				img.setAttribute('id', id);
			}
			return img;
		}
	});
})(jQuery);